<?php

namespace App\Admin\Controllers;

use App\Admin\Forms\Settings\Company;
use App\Admin\Forms\Settings\Manager;
use App\Admin\Forms\Settings\Website;
use App\Http\Controllers\Controller;
use App\Imports\Batch\SourceCode;
use App\Models\ProductModel;
use App\Models\ProductsBatchModel;
use App\Models\ProductsSaleModel;
use App\Models\ReportModel;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Widget;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use function app\Helpers\sys;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        //        $count['product'] = ProductModel::count();
        //        $count['report'] = ReportModel::count();
        //        $count['sale'] = ProductsSaleModel::count();
        //        $count['Batch'] = ProductsBatchModel::count();
        //
        $content->row("<h1 style='text-align: center;margin: 100px;'>欢迎来到后台管理系统</h1>")
            ->row(function ($row) {
                $row->column(3, new InfoBox('产品', 'product-hunt', 'aqua', '/admin/products', 6));
            });
        
        return $content;
    }
    
    public function query(Content $content)
    {
        try {
            $client   = new Client(['verify' => false]);
            $res      = $client->request(
                'POST',
                'https://tool.musicheng.com/lhkeyword/getlhkeywordlist',
                [
                    'multipart' => [
                        [
                            'name'     => 'sort',
                            'contents' => 'moods'
                        ],
                        [
                            'name'     => 'order',
                            'contents' => 'desc'
                        ],
                        [
                            'name'     => 'searchparams',
                            'contents' => '{"lhword":"水电费"}'
                        ],
                    ],
                    'proxy'     => [
                        'http' => '127.0.0.1:8888', //http协议的
                        //https协议的,带用户名密码验证的代理
                        //             'https' => 'http://username:password@localhost:9124',
                        'no'   => ['.mit.edu', 'foo.com']    // 无需代理的域名
                    ],
                    'headers'   => [
                        'User-Agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
                        //             'Accept'     => 'application/json',
                        //             'X-Foo'      => ['Bar', 'Baz']
                        'Cookie'     => "Hm_lvt_23c29ef18f57ef3419152a651c437547=1598629381; _ga=GA1.2.857115032.1598629384; _gid=GA1.2.784574927.1598629384; _gat=1; _gat_gtag_UA_129654797_1=1; lmkb=loginname=whjsdhr&chsavepsw=1&token=f881b239a4d12b698b044a4d3587026b&dt=1598888596; plcug=tik=M416ggkb6ccN688kk8ckM686k&token=04&isq=1&dt=1601221396; ASP.NET_SessionId=4lgcwrngji1hptudmoa2kqkl; otinfo=_siNt=1&_clri=5183398665563528685&_otm=1598629399; SignalRID=1_5183398665563528685; expcode5183398665563528685=expdt=2021-07-16&date=1598629399; Hm_lpvt_23c29ef18f57ef3419152a651c437547=1598629406"
                    ]
                ]
            );
            $response = $res->getBody()->getContents();
            $response = json_decode($response, true);
            if (!isset($response['Success']) || !$response['Success']) {
                throw new \Exception('获取失败');
            }
            dump($response);
            exit;
        } catch (\Throwable | \Exception $exception) {
            echo "出错了";
            $responseBody = $exception->getResponse()->getBody()->getContents();
            dump($responseBody);
            exit;
            //       //$responseBody = $exception->getResponse()->getBody(true);有的版本可能是这样
            //       //       preg_match_all('/<div class="text-tip[^>]*([\s\S]*?)<\/div>/i', $responseBody, $matches);
            //       preg_match_all('/<div class="text-tip">*([\s\S]*?)<\/div>/i', $responseBody, $matches);
            //       $matches = array_filter($matches);
            //       if ($matches) {
            //          dump($matches[1] ?? '请求错误1');
            //       }
            //       try {
            //          $responseBody = json_decode($responseBody, true);
            //          if (is_array($responseBody) && $responseBody) {
            //             dump($responseBody['code'][0] ?? '请求错误2');
            //             exit;
            //          }
            //          dump($responseBody);
            //          exit;
            //       } catch (\think\Exception | Throwable $e) {
            //          dump('请求错误3');
            //       }
            //       dump($responseBody);
            //       exit;
        }
        dump("d");
        exit;
        $source_code = request()->get('source_code');
        $html        = <<<eof
<div class="mailbox-controls with-border">
                <form method='get' action='/admin/query'>
                    <div class="input-group input-group-sm pull-right goto-url" style="width: 250px;margin-bottom: 10px;">
                        <input type="text" placeholder='输入溯源码' name="source_code" class="form-control pull-right" value="{$source_code}">

                        <div class="input-group-btn">
                            <button type="submit" class="btn btn-default"><i class="fa fa-arrow-right"></i></button>
                        </div>
                    </div>
                </form>
</div>
eof;
        $c           = $content
            ->title('我要查询')
            ->description('查询溯源码信息')
            ->row($html);
        
        if ($source_code) {//溯源码
            //查找销售记录
            $saleHistory = ProductsSaleModel::where('code', $source_code)
                //                ->select('sale_id', 'batch_id', 'customer_id', 'sale_num', 'sale_type', 'scan_times')
                ->first();
            if ($saleHistory) {
                $productBatch = ProductsBatchModel::where('batch_id', $saleHistory['batch_id'])
                    //                    ->select('batch_id', 'customer_id', 'product_id', 'unit', 'number', 'quality_result', 'quality_type', 'source', 'source_code', 'image', 'video', 'receive_time')
                    ->first();
            } else {//查找产品批次
                $productBatch = ProductsBatchModel::where('source_code', $source_code)
                    //                    ->select('batch_id', 'customer_id', 'product_id', 'unit', 'number', 'quality_result', 'quality_type', 'source', 'source_code', 'image', 'video', 'receive_time', 'scan_times')
                    ->first();
                if (!$productBatch) {//销售记录和产品批次都没有
                    return $c;
                }
                $saleHistory = ProductsSaleModel::where('batch_id', $productBatch['batch_id'])
                    //                    ->select('sale_id', 'batch_id', 'customer_id', 'sale_num', 'sale_type')
                    ->first();
            }
            $product = $saleHistory['product'] ?: $productBatch['product'];
            //            $customer    = $saleHistory['Customer'];
            
            $c->row(function (Row $row) use ($productBatch, $product, $saleHistory) {
                
                $row->column(4, function (Column $column) use ($productBatch, $product) {
                    $column->append(self::batch($productBatch, $product));
                });
                
                if ($saleHistory) {
                    $row->column(4, function (Column $column) use ($saleHistory, $product) {
                        $column->append(self::saleHistory($saleHistory, $product));
                    });
                }
                
                //                $row->column(4, function (Column $column) {
                //                    $column->append(Dashboard::dependencies());
                //                });
            });
        }
        
        return $c;
    }
    
    /**
     * 产品信息
     * @param ProductsBatchModel $batch
     * @param ProductModel       $product
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function batch(ProductsBatchModel $batch, ProductModel $product)
    {
        $objs = [
            ['name' => '产品名称', 'value' => $product['product_name']],
            ['name' => '产品类型', 'value' => $product['variety_name']],
            ['name' => '收货数量', 'value' => $batch['number'] . ProductsBatchModel::MAP_UNIT[$batch['unit']]],
            ['name' => '产品追溯码', 'value' => $batch['source_code']],
            ['name' => '来源', 'value' => ProductsBatchModel::MAP_SOURCE[$batch['source']]],
            ['name' => '产品追溯码', 'value' => $batch['source_code']],
            ['name' => '主体名称', 'value' => sys('subject_name')],
            ['name' => "主体地址", 'value' => sys('subject_address')],
            ['name' => '联系人姓名', 'value' => sys('contact_person')],
            ['name' => '联系方式', 'value' => sys('contact_phone')],
            ['name' => '主体身份码', 'value' => sys('subject_code')],
        ];
        
        $title = '产品信息';
        return view('admin.query', compact('objs', 'title'));
    }
    
    /**
     * 销售信息
     * @param ProductsSaleModel $history
     * @param ProductModel      $product
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public static function saleHistory(ProductsSaleModel $history, ProductModel $product)
    {
        $objs = [
            ['name' => '产品名称', 'value' => $product['product_name']],
            ['name' => '产品类型', 'value' => $product['variety_name']],
            ['name' => '数量', 'value' => $history['sale_num']],
            ['name' => '入市追溯码', 'value' => $history['code']],
            ['name' => '追溯类别', 'value' => $history['sale_type']],
        ];
        if ($history['customer_id']) {
            $customer = $history['Customer'];
            $extras   = [
                ['name' => '主体名称', 'value' => $customer['company_name']],
                ['name' => "主体地址", 'value' => $customer['company_address']],
                ['name' => '联系人姓名', 'value' => $customer['name']],
                ['name' => '联系方式', 'value' => $customer['phone']],
            ];
            $objs     = array_merge($objs, $extras);
        }
        $title = '销售信息';
        return view('admin.query', compact('objs', 'title'));
    }
    
    public function settings(Content $content)
    {
        return $content
            ->title('设置')
            ->body(Tab::forms([
                                  'website' => Website::class,
                                  'manager' => Manager::class,
                                  'company' => Company::class,
                              ]));
    }
}
